home *** CD-ROM | disk | FTP | other *** search
- Path: news1.intercall.com!usenet
- From: engevar@intercall.com (Steven Ovits)
- Newsgroups: comp.lang.c
- Subject: Re: Dynamic 2-D arrays
- Date: Fri, 29 Mar 1996 02:56:55 GMT
- Organization: Intercall Inc.
- Message-ID: <4jf9t1$98@news1.intercall.com>
- References: <40.69871.1612@channel1.com>
- NNTP-Posting-Host: ts2-112.intercall.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- dspse.bedford@channel1.com (Dspse Bedford) wrote:
-
- >I want to define a 2-D array through a pointer-to-pointer structure member
- >as shown below:
-
- >typedef struct
- >{ float **matrix;}Obj;
- >main()
- >{Obj *m;
- > int x=5;y=10;
- > m=(Obj *)malloc(sizeof(Obj));
- > *(m->matrix)=(float *)malloc(x*y*sizeof(float *));
- > ...
- > ...
- > return;}
-
- >if I index in the following way: m->matrix[i][j], how does it increment the
- >pointer to determine the memory location? If I have
- >m->matrix[1][2] and m->matrix[2][1] what is the difference?
-
- First, I hope you have some real memory at that location, you
- allocated the pointers but not the floats. You also have to point
- the float* to the memory allocated for the floats.
-
- The compiler treats a[][j] as if it were a type definition, and
- calculates a[i][j] as: *(a + i * sizeof(a[][j]) + j).
- You should notice that the compiler must know the number of
- elements in a row--in all rows except the first. That takes some
- getting used to, but consider how you would get to a[1][0][0][0]
- in a[][x][y][z] without knowing x, y, and z.
-
- Now you can try calculating m[1][2] and m[2][1].
-
- More formally, given float matrix[i][j],
- matrix[p][q] is evaluated as *( * (matrix+p) + q)
- but this hides the details.
-
- To answer your question, write a macro.
- #define idx2d(Array, i, j, dim1, type) \
- (type) ( (Array) + (((i) * (dim1)) + (j)) * sizeof(type) )
-
- >In the past, I would use something like whats below, but the difference is
- >I do now know ahead of time the Y_dimension or the X_dimension.
-
- >#define Y_DIM 10
- >#define X_DIM 5
- >typedef struct
- >{float *matrix[Y_DIM];}Obj;
- >main()
- >{
- > Obj *m;
- > m=(Obj *)malloc(sizeof(Obj));
- > for (i=0;i<Y_DIM;++i)
- > { m->matrix[i]=(float *)malloc(X_DIM*sizeof(float));}
- > ..
- > return;}
-
- >The above ofcourse indexes fine since I create an array of pointers of the
- >proper Y-dimension in my structure definition.
-
- >Any help would be appreciated.
-
- >Thank you,
- >Anastasios Maurudis
- >anastasios@dspse.com
- >DSP Software Engineering, Inc.
- >175 Middlesex Turnpike
- >Bedford, MA 01730
- >(617)275-3733
- >(617)275-4323 Fax
- >
-
- >---
- > * WR 1.32 # 331 * Blue Wave - what Smurfs do at a football game..
-
-
-